package cliente.android;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject; 
import android.util.Log;

public class SolicitaServer{
    DefaultHttpClient httpClient;
    HttpContext localContext;
    private String ret;
    HttpResponse response = null;
    HttpPost httpPost = null;
    HttpGet httpGet = null;
    String webServiceUrl;
 

    public SolicitaServer(String server)  throws Exception {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        httpClient = new DefaultHttpClient(params);
        localContext = new BasicHttpContext();
        webServiceUrl = server;
    }
 
    public String webGet(Map<String, String> solicitacao) throws Exception {
    	
    	String getUrl = criaUrlSolicitacao(solicitacao,webServiceUrl);
 
        httpGet = new HttpGet(getUrl);
        Log.e("WebGetURL: ",getUrl);
 
        try {
            response = httpClient.execute(httpGet);
        } catch (Exception e) {}
 
        try {
            ret = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {}
 
        return ret;
    }

	private String criaUrlSolicitacao(Map<String, String> solicitacao, String getUrl) {
        int i = 0;
        for (Map.Entry<String, String> param : solicitacao.entrySet()) {
            if(i == 0){
                getUrl += "?";
            }
            else{
                getUrl += "&";
            }
 
            try {
                getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
 
            i++;
        }
        return getUrl;
	}
 
}